<?php

namespace addons\Attend\api\modules\v1\controllers;

use common\helpers\ArrayHelper;
use Yii;
use yii\data\ActiveDataProvider;
use yii\db\Expression;
use yii\helpers\Json;
use api\controllers\OnAuthController;
use common\helpers\ResultHelper;
use common\enums\StatusEnum;
use addons\Attend\common\enums\CheckEnum;
use addons\Attend\common\enums\CheckStateEnum;
use addons\Attend\common\models\AttendCheck;
/**

 * @property \yii\db\ActiveRecord|\yii\base\Model $modelClass;
 * @author 古月 <21931118@qq.com>
 */
class CheckController extends OnAuthController
{
    public $modelClass = AttendCheck::class;

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = ['index', 'view'];

    /**
     * 首页
     *
     * @return ActiveDataProvider
     */
    public function actionIndex()
    {
        if (Yii::$app->request->get('date') == '9999')
            $created_time = '';
        else {
            $start = strtotime(Yii::$app->request->get('date') . ' 00:00:01');
            $end = strtotime(Yii::$app->request->get('date') . ' 23:59:59');
            $created_time = ['between', 'created_at', $start, $end];
        }
        return new ActiveDataProvider([
            'query' => $this->modelClass::find()
                ->andWhere($created_time)
                ->andWhere(['member_id' => Yii::$app->user->identity->member_id])
                ->andFilterWhere(['type' => Yii::$app->request->get('type')])
                ->andFilterWhere(['state' => Yii::$app->request->get('state')])
//                ->andFilterWhere(['classes_id' => Yii::$app->request->get('classes_id')])
                ->orderBy('id desc')
                ->with('member', 'attendClasses')
                ->asArray(),
            'pagination' => [
                'pageSize' => $this->pageSize,
                'validatePage' => false,// 超出分页不返回data
            ],
        ]);
    }

    public function actionCreate()
    {
        /* @var $model \yii\db\ActiveRecord */
        $model = new $this->modelClass();
        $model->attributes = Yii::$app->request->post();
        //判断是否重复签到
        $check = \addons\Attend\common\models\AttendCheck::find()->andWhere(['member_id' => Yii::$app->user->identity->member_id, 'type' => $model->type, 'classes_id' => $model->classes_id])->one();
        if ($check && $check->type == 0 && date("Y-m-d", $check->created_at) == date("Y-m-d", time()))
            return ResultHelper::json(422, "该班次已经签到了，不能重复签到！");
        if ($check && $check->type == 1 && date("Y-m-d", $check->created_at) == date("Y-m-d", time()))
            return ResultHelper::json(422, "该班次已经签退了，不能重复签退！");
        //判断是否已签到
        $start = strtotime(date("Y-m-d", time()) . ' 00:00:01');
        $end = strtotime(date("Y-m-d", time()) . ' 23:59:59');
        $created_time = ['between', 'created_at', $start, $end];
        $check = \addons\Attend\common\models\AttendCheck::find()
            ->andWhere(['member_id' => Yii::$app->user->identity->member_id, 'type' => 0, 'classes_id' => $model->classes_id])
            ->andWhere($created_time)
            ->one();
        if (!$check && $model->type == 1)
            return ResultHelper::json(422, "您今天还没有签到，请先签到打卡！");
        //判断班次
        $where = new Expression("FIND_IN_SET(:supplier, check_date)", [":supplier" => date("Y-m-d", time())]);
        $plans = \addons\Attend\common\models\AttendPlan::find()->andWhere($where)->andWhere(['member_id' => Yii::$app->user->identity->member_id, 'classes_id' => $model->classes_id])->one();
        if (!$plans)
            return ResultHelper::json(422, "没有该班次！");
        else if (($model->type == CheckEnum::SignIn)) {
            if (strtotime(date("Y-m-d", time()) . ' ' . $plans->begin_time) < time())
                $model->state = CheckStateEnum::Late;
            else $model->state = CheckStateEnum::Normal;
        } else if (($model->type == CheckEnum::SignOut)) {
            if (strtotime(date("Y-m-d", time()) . ' ' . $plans->end_time) > time())
                $model->state = CheckStateEnum::Early;
            else $model->state = CheckStateEnum::Normal;
        }
        $model->begin_time = $plans->begin_time;
        $model->end_time = $plans->end_time;
        if (!$model->save()) {
            return ResultHelper::json(422, $this->getError($model));
        }
        return $model;
    }

    public function actionView($id)
    {
        $model = $this->modelClass::find()->where(['id' => $id, 'status' => StatusEnum::ENABLED,])
            ->with('member')->asArray()->one();
        return $model;
    }
    public function actionState()
    {
        return ArrayHelper::arrayToArrays(\addons\Attend\common\enums\CheckStateEnum::getMap());
    }
    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        // 方法名称
        if (in_array($action, ['delete'])) {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}